package me.tuyou.es.jest.service;

import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import me.tuyou.es.jest.dto.Hotel;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class EsService {

    @Autowired
    private JestClient jestClient;

    public List<Hotel> getHotelFromTitle(String keyword) {
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", keyword);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(queryBuilder);
        Search search = new Search.Builder(sourceBuilder.toString()).addIndex("hotel").build();

        try {
            SearchResult result = jestClient.execute(search);
            if (result.isSucceeded()) {
                return result.getSourceAsObjectList(Hotel.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
